package thread;

import java.util.Arrays;

public class ProductConsumerSyn {
    public static void main(String[] args){

        Clerk clerk = new Clerk();
        Product product = new Product(clerk);
        Consumer consumer = new Consumer(clerk);

        new Thread(product,"生产者A").start();
        new Thread(consumer,"消费者B").start();
        new Thread(product,"生产者C").start();
        new Thread(consumer,"消费者D").start();
    }
}


class Product implements  Runnable{

    private Clerk clerk;

    public Product(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {

        for(int i = 0;i<20;i++){
            //睡眠0.2s
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.product();
        }
    }
}
class Consumer implements  Runnable{

    private Clerk clerk;

    public Consumer(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for(int i = 0;i<20;i++){
            clerk.sale();
        }
    }
}
//店员
class Clerk{
    private int product=0;
    //进货 方法使用synchronized 修饰
    public synchronized void product(){
        // 注意可能已经通过if判断，产生虚假唤醒，加上while唤醒后继续判断
        while (product>=1){
            System.out.println("产品已满");
            // 由于循环次数和产品数量不一致，会出现过剩生产和超额消费问题，此时就需要进程间通信
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            }
            System.out.println(Thread.currentThread().getName()+":"+(++product));
            this.notifyAll();
    }
    //卖货 方法使用synchronized 修饰
    public synchronized void sale(){
        while(product<=0){
            System.out.println("缺货！");
            // 由于循环次数和产品数量不一致，会出现过剩生产和超额消费问题，此时就需要进程间通信
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            }
            System.out.println(Thread.currentThread().getName()+":"+(--product));
            this.notifyAll();
    }
}